﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Center.lib.utils.json;
using Center.lib.utils.log;

namespace Center.lib.utils.http
{
    public static class HttpUtils
    {
        public static async Task<string> PostData(string url, Dictionary<string, string> headers = null)
        {
            try
            {
                var encoding = Encoding.GetEncoding("UTF-8");
                var parameters = new Dictionary<string, string>();
                var response = HttpWebResponseUtility.CreatePostHttpResponse(url, parameters, null, null, encoding, null, headers);
                var content = HttpWebResponseUtility.GetResponseContent(response, encoding);
                return content;
            }
            catch (Exception e)
            {
                LogHelper.WriteLog(@"访问异常：", e);
                return null;
            }
        }

        public static async Task<string> PostData(string url, Dictionary<string, string> parameters, Dictionary<string, string> headers = null)
        {
            var encoding = Encoding.GetEncoding("UTF-8");
            var response = HttpWebResponseUtility.CreatePostHttpResponse(url, parameters, null, null, encoding, null, headers);
            var content = HttpWebResponseUtility.GetResponseContent(response, encoding);
            return content;
        }
        public static async Task<string> PostData(string url, String json, Dictionary<string, string> headers = null)
        {
            try
            {
                var encoding = Encoding.GetEncoding("UTF-8");
                var response = HttpWebResponseUtility.CreatePostHttpResponse(url, json, null, null, encoding, null, headers);
                var content = HttpWebResponseUtility.GetResponseContent(response, encoding);
                return content;
            }
            catch (Exception e)
            {
                LogHelper.WriteLog(@"访问异常：", e);
                return "访问异常";
            }
        }

        /// <summary>
        /// post协议
        /// </summary>
        /// <param name="url"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        public static async Task<string> PostData(string url, object json, Dictionary<string, string> headers = null)
        {
            String jsonData = JsonHelper.ToJson(json);
            try
            {
                var encoding = Encoding.GetEncoding("UTF-8");
                var response = HttpWebResponseUtility.CreatePostHttpResponse(url, jsonData, null, null, encoding, null, headers);
                var content = HttpWebResponseUtility.GetResponseContent(response, encoding);
                return content;
            }
            catch (Exception e)
            {
                LogHelper.WriteLog(@"访问异常：", e);
                return "访问异常";
            }
        }
    }
}
